using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Alidns20150109;
using AlibabaCloud.SDK.Alidns20150109.Models;
using AlibabaCloud.TeaUtil;
using AlibabaCloud.TeaUtil.Models;
using AliCloudDNSResolution.Application.Contract;
using AliCloudDNSResolution.Application.Contract.Modules;
using Microsoft.Extensions.Options;
using Tea;

namespace AliCloudDNSResolution.Application;

/// <inheritdoc />
public class DnsResolutionService 
{
    private readonly AliCloudAccessOptions _cloudAccessOptions;
    public DnsResolutionService(IOptions<AliCloudAccessOptions> cloudAccessOptions)
    {
        _cloudAccessOptions = cloudAccessOptions.Value;
    }

    private Client CreateClient()
    {
        var config = new Config
        {
            Endpoint = "alidns.cn-hangzhou.aliyuncs.com",
            AccessKeyId = _cloudAccessOptions.AccessKey,
            AccessKeySecret = _cloudAccessOptions.AccessKeySecret,
        };

        return new Client(config);
    }

    /// <inheritdoc />
    public Task<dynamic> GetResolutionDetailAsync()
    {
        throw new NotImplementedException();
    }

    /// <inheritdoc />
    public async Task<string> UpdateDomainRecordAsync(UpdateDomainRecordInput input)
    {
        var client = CreateClient();
        
        return await CreateUpdateDomainRecordAsync(client,input);
    }

    private Task<string> CreateUpdateDomainRecordAsync(Client client,UpdateDomainRecordInput input)
    {

        var updateDomainRecordRequest = new UpdateDomainRecordRequest
        {
            RR = input.RR,
            RecordId = input.RecordId,
            Type = input.Type,
            Value = input.Value,
            Line = input.Line.ToString(),
            Priority = input.Priority
        };

        if (!string.IsNullOrEmpty(input.Lang))
        {
            updateDomainRecordRequest.Lang = input.Lang;
        }

        if (!string.IsNullOrEmpty(input.UserClientIp))
        {
            updateDomainRecordRequest.UserClientIp = input.UserClientIp;
        }
        
        RuntimeOptions runtime = new RuntimeOptions();

        string recordId =string.Empty ;
        try
        {
            // 复制代码运行请自行打印 API 的返回值
            recordId =  client.UpdateDomainRecordWithOptions(updateDomainRecordRequest, runtime).Body.RecordId;
        }
        catch (TeaException error)
        {
            // 如有需要，请打印 error
            Common.AssertAsString(error.Message);
        }
        catch (Exception _error)
        {
            TeaException error = new TeaException(new Dictionary<string, object>
            {
                { "message", _error.Message }
            });
            // 如有需要，请打印 error
            Common.AssertAsString(error.Message);
        }

        return Task.FromResult(recordId);
    }

    /// <inheritdoc />
    public async Task<List<string>> UpdateDomainRecordListAsync(List<UpdateDomainRecordInput> input)
    {
        var client = CreateClient();

        var ids = new List<string>();

        foreach (var domainRecordInput in input)
        {
            var id = await CreateUpdateDomainRecordAsync(client,domainRecordInput);
            ids.Add(id);
        }

        return ids;
    }

    public Task<string> CreateDomainRecordAsync(UpdateDomainRecordInput input)
    {
        var client = CreateClient();
        
        var addDomainRecordRequest = new AddDomainRecordRequest()
        {
            DomainName = _cloudAccessOptions.DomainName,
            RR = input.RR,
            Type = input.Type,
            Line =input.Line.ToString(),
            TTL = input.Ttl,
            Priority = input.Priority,
            Value = input.Value,
        };
        var runtime = new RuntimeOptions();
        var result =  client.AddDomainRecordWithOptions(addDomainRecordRequest, runtime);

        return Task.FromResult(result.Body.RecordId);
    }

    /// <inheritdoc cref="" />
    public Task<List<DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecords.DescribeDomainRecordsResponseBodyDomainRecordsRecord>> GetDescribeDomainRecordsAsync()
    {
        var client = CreateClient();

        var describeDomainRecordsRequest = new DescribeDomainRecordsRequest
        {
            DomainName = _cloudAccessOptions.DomainName,
        };

        var runtime = new RuntimeOptions();

        var result = client.DescribeDomainRecordsWithOptions(describeDomainRecordsRequest, runtime);

        return Task.FromResult(result.Body.DomainRecords.Record);
    }
}